import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import { fromLonLat } from 'ol/proj';
import Zoom from 'ol/control/Zoom';
import { defaults as defaultControls, Attribution } from 'ol/control';
import { Observable, Subject } from 'rxjs';
import { retry } from 'rxjs/operators';
import { ToolsService, BullySubjectService } from 'app/shared/service';
import { DataVisualizationService } from '../../dataVisualization.service';
@Component({
    selector: 'itmp-traffic-situation',
    templateUrl: './traffic-situation.component.html',
    styleUrls: ['./traffic-situation.component.css']
})
export class TrafficSituationComponent implements OnInit, AfterViewInit {
    legends = [
        {
            value: 'Stopped',
            status: 'stopped'
        },
        {
            value: 'Heavy_Traffic',
            status: 'HeavyTraffic'
        },
        {
            value: 'Medium_Traffic',
            status: 'MediumTraffic'
        },
        {
            value: 'Light_Traffic',
            status: 'LightTraffic'
        }
    ];
    mapStyle = {
        width: '100%',
        height: '250px',
        margin: '0 auto',
        borderRadius: '1px',
        backgroundColor: '#383d75' //颜色配置
    };
    lonlat = {
        london: fromLonLat([-0.12755, 51.507222]),
        moscow: fromLonLat([37.6178, 55.7517]),
        istanbul: fromLonLat([28.9744, 41.0128]),
        rome: fromLonLat([12.5, 41.9]),
        bern: fromLonLat([7.4458, 46.95]),
        singapore: fromLonLat([107.0841908454895, 20.954500436782837])
    };
    mapOptions: any;
    view: any;
    zoom: any;
    map: any;
    control: any;
    style: any;
    currentCoords = [107.085144, 20.974674];
    constructor(private tools: ToolsService, private ds: DataVisualizationService) {}
    ngOnInit() {
        // this.initMap();
    }
    ngAfterViewInit(): void {
        setTimeout(() => this.initMap());
        // setTimeout(() => this.panToLon(), 1000);
    }
    onReady(_e) {
        if (_e) {
            this.map = _e;
            this._registerTrafficLayer();
        }
    }
    initMap() {
        this.view = new View({
            projection: 'EPSG:4326',
            center: this.currentCoords,
            zoom: 12,
            minZoom: 0,
            maxZoom: 28
        });
        this.control = defaultControls({ attribution: false, zoom: false }).extend([]);
        this.mapOptions = {
            // use defaultOption in ol-map.component
            // layers: [
            //     new TileLayer({
            //         source: new OSM()
            //     })
            // ],
            controls: this.control,
            view: this.view
        };
    }
    // 定位到位置
    panToLon() {
        if (this.view) {
            this.view.animate({
                center: this.lonlat.singapore,
                zoom: 15
            });
        }
    }
    // 放大
    toLargeZoom() {
        if (this.view) {
            this.view.animate({
                zoom: this.view.getZoom() + 1,
                duration: 100
            });
        }
    }
    // 缩小
    toSmallZoom() {
        if (this.view) {
            this.view.animate({
                zoom: this.view.getZoom() - 1,
                duration: 100
            });
        }
    }
    createLocationObservable(): Observable<any> {
        return Observable.create(observer => {
            // const { next, error } = observer;
            const geoOptions = {
                enableHighAccuracy: true,
                maximumAge: 30000,
                timeout: 5000
            };

            if ('geolocation' in navigator) {
                navigator.geolocation.getCurrentPosition(
                    position => observer.next(position),
                    error => observer.error('locate faild'),
                    geoOptions
                );
            } else {
                observer.error('locate faild');
            }
        });
    }
    // 获取地理定位
    geolocation() {
        this.createLocationObservable()
            .pipe(retry(5))
            .subscribe(
                data => {
                    this.currentCoords = [
                        this.tools.calc(data, 'coords.longitude', 107.085197),
                        this.tools.calc(data, 'coords.latitude', 20.952057)
                    ];
                    this.center(this.currentCoords);
                    // set locate marker
                    // this.setLocateMarker(this.currentCoords);
                },
                err => {
                    /* this.msg.notify({
						type: 'warning',
					}) */
                    alert('locate failed!');
                }
            );
    }
    // 标记定位中心点
    center(coordinates: number[]): void {
        if (this.view) {
            this.view.animate({
                center: coordinates
            });
        }
    }
    // 设置定位点 locate
    // setLocateMarker(coordinates: number[]) {
    //     const features: FeatureType = {
    //         longitude: coordinates[0].toPrecision(9),
    //         latitude: coordinates[1].toPrecision(9),
    //         linkID: '',
    //         roadName: '',
    //         available: false
    //     };

    //     // 查询地理位置信息
    //     this.mapDataService.getLocalInfo(coordinates).subscribe(res => {
    //         if (this.tools.calc(res, 'features', []).length > 0) {
    //             const props = res.features[0].properties;
    //             features.available = true;
    //             features.linkID = props.linkID;
    //             features.roadName = props.name;
    //         }
    //         this.setMarker(MARKER_TYPE.LOCATE_MARKER, {
    //             coordinates,
    //             features
    //         });
    //     });
    // }
    // 注册交通图层
    private _registerTrafficLayer() {
        const layer = this.ds.getTrafficDataLayer();
        this.map.addLayer(layer);
        // layer.setSource(null);
        // layer.setSource();
        layer.setVisible(true);
    }
}
